package cc.common.types.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.HashMap;
import java.util.Map;

@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    /**
     * 实体类校验错误
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<?> handleValidationException(MethodArgumentNotValidException ex) {
        Map<String, Object> errors = new HashMap<>();

        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });

        return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
     }

    /**
     * 实体类校验错误 AccessDeniedException
     */
    @ExceptionHandler(AccessDeniedException.class)
    public ResponseEntity<?> handAccessDeniedException(AccessDeniedException ex) {
        Map<String, Object> errors = new HashMap<>();

        return new ResponseEntity<>(errors, HttpStatus.UNAUTHORIZED);
    }

    /**
     * 实体类校验错误 AccessDeniedException
     */
    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handException(AccessDeniedException ex) {

        return new ResponseEntity<>("服务器异常",HttpStatus.INTERNAL_SERVER_ERROR);
    }
}